package com.onenine.app.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Pair;
import android.view.View;
import android.widget.ImageView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.onenine.app.R;
import com.onenine.app.activity.MainActivity;
import com.onenine.app.activity.PostDetailActivity;
import com.onenine.app.adapter.CRecAdapter;
import com.onenine.app.adapter.MultiImageAdapter;
import com.onenine.app.event.ImageTransitionEvent;
import com.onenine.app.event.RefreshEvent;
import com.onenine.app.model.CoterieItem;
import com.onenine.app.model.PostItem;
import com.onenine.app.request.GetPostRequest;
import com.onenine.app.response.GetPostResponse;
import com.onenine.app.utils.DataType;
import com.onenine.app.utils.UrlConfig;
import com.onenine.app.view.TransitionViewHelper;
import com.onenine.app.view.nineimage.NineGridImageView;
import com.onenine.base.base.BasePageListFragment;
import com.onenine.base.okhttp.OkCallback;
import com.onenine.base.okhttp.OkRequest;
import com.onenine.base.utils.AppConfig;
import com.onenine.base.view.PullRefreshRecyclerView;
import com.onenine.chat.rongcloud.RcUser;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import cn.jzvd.JZMediaManager;
import cn.jzvd.Jzvd;
import cn.jzvd.JzvdMgr;

/**
 * 推荐列表
 */
public class CRecListFragment extends BasePageListFragment implements
        RecyclerView.OnChildAttachStateChangeListener, MultiImageAdapter.OnItemImageClickListener {

    private CoterieItem mCoterieItem;
    private NineGridImageView mClickMultiImageView;

    public static Fragment newInstance(CoterieItem coterieItem) {
        CRecListFragment fragment = new CRecListFragment();
        Bundle args = new Bundle();
        args.putSerializable("data", coterieItem);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        mCoterieItem = (CoterieItem) getArguments().getSerializable("data");
        if (mCoterieItem == null) {
            throw new IllegalArgumentException("圈子项不能为空");
        }
        EventBus.getDefault().register(this);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected Pair<PullRefreshRecyclerView, RecyclerView.Adapter> initPullRefreshView(View view) {
        return new Pair(view.findViewById(R.id.pull_to_refresh_layout), new CRecAdapter(this));
    }

    @Override
    public void initData() {
        super.initData();
        mPullRefreshView.postDelayed(new Runnable() {
            @Override
            public void run() {
                loadPageData(1);
            }
        }, 600);
    }

    @Override
    protected void initListener() {
        super.initListener();
        mPullRefreshView.addOnChildAttachStateChangeListener(this);
    }

    @Override
    protected void loadPageData(int pageNum) {
        GetPostRequest request = new GetPostRequest();
        request.setUserId(RcUser.getInstance().getUserId());
        request.setCoteriePkId(mCoterieItem.getCoteriePkId());
        request.setPageNum(pageNum);
        request.setPageSize(AppConfig.PAGE_SIZE);
        OkRequest.getInstance().withUrl(UrlConfig.GET_POST_LIST)
                .withRequest(request).doRequest(CRecommendFragment.class.getSimpleName(), new OkCallback<GetPostResponse>() {
            @Override
            public void onResponse(GetPostResponse response, String srcData) {
                dismissRefreshStatus();
                if (response.isSuccess()) {
                    notifyDataSuccess(response.getPostItemList());
                } else {
                    notifyDataFailure();
                }
            }
        });
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        PostItem postItem = ((PostItem) adapter.getItem(position));
        PostDetailActivity.launchActivity(getActivity()
                , postItem.getPostPkId(), postItem.getPostType() == DataType.POST_TOPIC
                        ? DataType.POST_TOPIC : DataType.POST_ASK, postItem.getSpanType());
    }

    @Override
    public void onItemClick(Context context, NineGridImageView multiImageView, ImageView imageView) {
        mClickMultiImageView = multiImageView;
    }

    @Override
    protected int getLayout() {
        return R.layout.layout_pull_refresh_view;
    }

    @Override
    public void onChildViewAttachedToWindow(View view) {
    }

    @Override
    public void onChildViewDetachedFromWindow(View view) {
        Jzvd jzvd = view.findViewById(R.id.jz_video_view);
        if (jzvd != null && jzvd.jzDataSource != null
                && jzvd.jzDataSource.containsTheUrl(JZMediaManager.getCurrentUrl())) {
            Jzvd currentJzvd = JzvdMgr.getCurrentJzvd();
            if (currentJzvd != null && currentJzvd.currentScreen != Jzvd.SCREEN_WINDOW_FULLSCREEN) {
                Jzvd.releaseAllVideos();
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(RefreshEvent event) {
        if (event.type == DataType.REFRESH_POST_PUBLISH_SUCCESS) {
            onRefresh();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(ImageTransitionEvent event) {
        if (TextUtils.equals(event.eventName
                , MainActivity.class.getSimpleName()) && event.position >= 0) {
            //多图查看返回
            if (mClickMultiImageView != null) {
                TransitionViewHelper.onActivityReenter(getActivity()
                        , mClickMultiImageView.getImageView(event.position));
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

}
